﻿
using DG.Tweening;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class UIBattleNetDelay : UIObject
{
    public Text textDelay;
    private Tweener _tweer1;
    private Sequence _sequence;
    private float _time = 10;
    protected override void onVisible()
    {
        base.onVisible();
#if false
        InvokeSendHandshake();  
#else
        DoAction();
#endif
        Facade.Instance.RegistNetEvent(nameof(handshake_rsp), OnHandleHandshakeRsp);
    }

    protected override void OnInvisible()
    {
        base.OnInvisible();
#if false
        CancelInvoke(nameof(InvokeSendHandshake));
#else
        _tweer1?.Kill();
        _tweer1 = null;
        _sequence?.Kill();
        _sequence = null;
#endif
        Facade.Instance.UnRegistNetEvent(nameof(handshake_rsp), OnHandleHandshakeRsp);
    }

    private void OnHandleHandshakeRsp(System.Object data)
    {
        DoAction();
    }

    private void DoAction()
    {
        _tweer1?.Kill();
        textDelay.color = Color.green;
        _tweer1 = textDelay.DOColor(Color.red, _time);

        _sequence?.Kill();
        textDelay.text = _time.ToString();
        _sequence = DOTween.Sequence(textDelay);
        for (int i = (int)_time; i > -1; i--)
        {
            _sequence.Append(textDelay.DOText(i.ToString(), 1));
        }
    }
#if false
    private void InvokeSendHandshake()
    {
        _time = Time.timeSinceLevelLoad;
        // Invoke(nameof(NetIsTooLate), 4);
        if (WebSocketClient.Instance.state == UnityWebSocket.WebSocketState.Open)
            WebSocketClient.Instance.SendMsgName("handshake");
        else
            Invoke(nameof(InvokeSendHandshake), 15);
    }

    private void OnHandleHandshakeRsp(System.Object data)
    {
       // CancelInvoke(nameof(NetIsTooLate));

        var rsp = data as handshake_rsp;
        var delay = Mathf.RoundToInt((Time.timeSinceLevelLoad - _time) * 1000);
        textDelay.text = string.Format("{0}ms", delay);
        if(delay > 400)
        {
            textDelay.color = Color.red;
        }
        else if (delay > 200)
        {
            textDelay.color = Color.yellow;
        }
        else
        {
            textDelay.color = Color.green;
        }
        Invoke(nameof(InvokeSendHandshake), 15);
        //Debug.Log("OnHandleHandshake time:" + Time.timeSinceLevelLoad + " rsp:" + rsp.msg);
    }

    //private void NetIsTooLate()
    //{
    //    textDelay.text = XLocalization.Get("网络出错,请重启");
    //    UIDialog.Instance.Show(XLocalization.Get("错误"), XLocalization.Get("网络出错了，如果不能继续玩，请重启游戏"), null, null);
    //    //textDelay.color = Color.red;
    //    Sequence seq = DOTween.Sequence();
    //    for (int i = 0; i < 3; i++)
    //    {
    //        seq.Append(textDelay.DOColor(Color.red, 1));
    //        seq.Append(textDelay.DOColor(Color.yellow, 1));
    //    }
    //    seq.Append(textDelay.DOColor(Color.red, 1));
    //}
#endif
}
